<template>
  <div>
    <router-view>
      <div v-if="stated">
        <el-card class="box-card">
          <template #header>
            <div style="width: 100%; display: flex; justify-content: space-between">
              <div style="font-size: 20px; font-weight: 600">管理员管理</div>
              <div style="width: 20%; display: flex; justify-content: flex-end">
                <el-button type="primary" @click="add_up">新增用户信息</el-button>
              </div>
            </div>
            <div style="height: 2vh"></div>
            <div style="display: flex; align-items: center">
              <div style="display: flex; align-items: center">
                <el-input v-model="input" placeholder="输入医生名称" clearable style="width: 250px" @input="docsearch" />
                <div style="width: 8px"></div>
                <el-select v-model="switdh" class="m-2" placeholder="请选择账号状态" clearable style="width: 240px"
                  @change="docsearch">
                  <el-option label="开启" value="1" />
                  <el-option label="关闭" value="2" />
                </el-select>
                <div style="width: 8px"></div>
              </div>
            </div>
          </template>
          <div>
            <el-table ref="multipleTableRef" style="width: 100%" stripe
              :data="tableData.slice((currentPage4 - 1) * pageSize4, currentPage4 * pageSize4)" v-loading="loading"
              max-height="60vh">
              <el-table-column label="序号" property="id" width="60" align="center" fixed />
              <el-table-column property="card" label="头像" width="140" align="center">
                <template #default="{ row }">
                  <el-image style="width: 50px; height: 50px; border-radius: 100%" :src="url + row.img" />
                </template>
              </el-table-column>
              <el-table-column label="用户名称" property="name" align="center" fixed />
              <el-table-column label="账号" property="account" align="center" fixed />
              <el-table-column property="tel" label="手机号" show-overflow-tooltip align="center" />
              <el-table-column property="status" label="是否开启" show-overflow-tooltip align="center">
                <template #default="{ row }">
                  <el-switch v-model="row.defaule" @change="switch_button(row)" />
                </template>
              </el-table-column>
              <el-table-column property="create_time" label="添加时间" show-overflow-tooltip align="center" />
              <el-table-column fixed="right" label="操作" width="120" align="center">
                <template #default="{ row }">
                  <div style="width: 100%; display: flex; justify-content: space-around">
                    <el-button type="primary" plain size="small"
                      @click="edit_cenyet(row)">编辑</el-button>
                    <el-button type="danger" plain size="small"
                      @click="delete_cenyet(row)">删除</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div style="height: 1vh"></div>
            <div style="display: flex; justify-content: center">
              <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
                :page-sizes="[10, 20, 50, 100]" :small="small" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="tableData.length" />
            </div>
          </div>
        </el-card>
      </div>
    </router-view>
    <!-- 添加，编辑弹出层 -->
    <el-dialog v-model="dialogVisible" :title="text_up" top="3vh" width="50%" :before-close="handleClose">
      <!-- <template #footer> -->
      <el-form ref="ruleFormRefs" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
        :size="formSize" status-icon>
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户账号" prop="account">
          <el-input v-model="ruleForm.account" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input type="password" v-model="ruleForm.password" placeholder="请输入用户密码" />
        </el-form-item>
        <el-form-item label="用户类型" prop="count">
          <el-select v-model="ruleForm.count" placeholder="请选择用户权限">
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in role_list" :key="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户手机号" prop="tel">
          <el-input type="tel" v-model="ruleForm.tel" placeholder="请输入用户手机号" />
        </el-form-item>
        <el-form-item label="头像" prop="fileList">
          <el-upload v-model:file-list="ruleForm.fileList" action="https://lxt.jingyi.icu/pc/Fileimg/file"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-success="handleSuccess" limit="1" :class="{ hide_box: upload_btn }">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="delivery">
          <el-switch v-model="ruleForm.delivery" />
        </el-form-item>

        <el-form-item>
          <div style="width: 100%; display: flex; justify-content: flex-end">
            <el-button @click="submitForm(ruleFormRefs)"> 取消 </el-button>
            <el-button type="primary" @click="resetForm(ruleFormRefs)">确认</el-button>
          </div>
        </el-form-item>
      </el-form>
      <!-- </template> -->
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { admin, admin_edit, role, delete_admin } from '@/api/prople';
import { depart } from '@/api/departMents';
import { Plus, Delete, Edit } from '@element-plus/icons-vue';
const multipleTableRef = ref();
const url = ref('https://lxt.jingyi.icu');
const input = ref('');
const switdh = ref();
const tableData = ref([]);
const currentPage4 = ref(1);
const pageSize4 = ref(10);
const options = ref([]);
const datesearch = ref([]);
const stated = ref(true);
const loading = ref(true);
const dialogVisible = ref(false);
const text_up = ref('添加');
const formSize = ref('default');
const ruleFormRefs = ref();
const role_list = ref();
const edit_id = ref(0);
const ruleForm = ref({
  name: '',
  account: '',
  count: '',
  password: '',
  delivery: false,
  tel: '',
  fileList: [],
});

const rules = reactive({
  name: [
    { required: true, message: '请输入用户的名称', trigger: 'blur' },
    { min: 3, message: '最少输入3个字', trigger: 'blur' },
  ],
  account: [
    { required: true, message: '请输入用户账号', trigger: 'blur' },
    { min: 3, message: '最少输入3个字', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入用户密码', trigger: 'blur' },
    { min: 6, message: '最少输入6个字', trigger: 'blur' },
  ],
  count: [{ required: true, message: '请选择角色类型', trigger: 'blur' }],
  tel: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' },
  ],
  fileList: [{ required: true, message: '请上传图片', trigger: 'blur' }],
});
roles();
// 角色列表
function roles() {
  role()
    .then((res) => {
      console.log(res);
      role_list.value = res.data;
      console.log(role_list.value);
    })
    .catch((err) => {
      console.log(err);
    });
}

payment();
function payment() {
  admin().then((res) => {
    console.log(res);
    for (let i in res.data) {
      if (res.data[i].status == 1) {
        res.data[i].defaule = true;
      } else {
        res.data[i].defaule = false;
      }
    }
    tableData.value = res.data;
    datesearch.value = res.data;
    loading.value = false;
  });
}
departs();
function departs() {
  depart().then((res) => {
    console.log(res);
    for (const dataItem of res.data) {
      options.value.push({ value: dataItem.id, label: dataItem.name });
    }
  });
}
const upload_btn = ref(false);

// 上传成功
const handleSuccess = () => {
  // 上传成功后，隐藏上传按钮
  upload_btn.value = true;
};
// 移出时触发
const handleRemove = () => {
  upload_btn.value = false;
};
// 搜索
function docsearch() {
  console.log(input.value);
  console.log(datesearch.value);
  const obj = {
    name: input.value,
    status: switdh.value,
  };
  const result = filter(obj, datesearch.value);
  console.log(result, 3333);
  tableData.value = result;
}

const filter = (condition, data) => {
  return data.filter((item) => {
    return Object.keys(condition).every((key) => {
      return String(item[key])
        .toLowerCase()
        .includes(String(condition[key]).trim().toLowerCase());
    });
  });
};
// 开关
function switch_button(item) {
  console.log(item);
  admin_edit({
    img: item.img,
    name: item.name,
    account: item.account,
    role: item.role,
    tel: item.tel,
    pass: item.pass,
    status: item.defaule == true ? 1 : 2,
    id: item.id,
  })
    .then((res) => {
      console.log(res);
      payment();
         ElMessage.success('操作成功');
    })
    .catch((err) => {
      console.log(err);
    });
}

// 添加弹出
const add_up = () => {
  dialogVisible.value = true;
  ruleFormRefs.value.clearValidate();
  ruleForm.value = {};
  upload_btn.value = false;
  edit_id.value = 0;
};
// 编辑
const edit_cenyet = (item) => {
  dialogVisible.value = true;
  upload_btn.value = true;
  console.log(item);
  ruleForm.value = {
    fileList: [
      {
        url: url.value + item.img,
      },
    ],
    name: item.name,
    account: item.account,
    count: item.role,
    tel: item.tel,
    password: item.show_pass,
    delivery: item.defaule == 1 ? true : false,
    id: item.id,
  };
  edit_id.value = item.id;
  ruleFormRefs.value.clearValidate();
  console.log(ruleForm.value);
};
// 提交
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    console.log(valid);
    // if (valid) {
    console.log('submit!');
    if (edit_id.value == 0) {
      admin_edit({
        img: ruleForm.value.fileList[0].response.data.url,
        name: ruleForm.value.name,
        account: ruleForm.value.account,
        role: ruleForm.value.count,
        tel: ruleForm.value.tel,
        pass: ruleForm.value.password,
        status: ruleForm.value.delivery == true ? 1 : 2,
        id: ruleForm.value.id,
      })
        .then((res) => {
          console.log(res);
          dialogVisible.value = false;
          ElMessage({
            message: '添加成功',
            type: 'success',
          });
          payment();
        })
        .catch((err) => {
          console.log(err);
          dialogVisible.value = false;
          ElMessage.error('添加失败');
        });
    } else {
      admin_edit({
        img:
          ruleForm.value.fileList[0].response !== undefined
            ? ruleForm.value.fileList[0].response.data.url
            : ruleForm.value.fileList[0].url.substr(
              ruleForm.value.fileList[0].url.indexOf('/up')
            ),
        name: ruleForm.value.name,
        account: ruleForm.value.account,
        role: ruleForm.value.count,
        tel: ruleForm.value.tel,
        pass: ruleForm.value.password,
        status: ruleForm.value.delivery == true ? 1 : 2,
        id: edit_id.value,
      })
        .then((res) => {
          console.log(res);
          dialogVisible.value = false;
          ElMessage({
            message: '编辑成功',
            type: 'success',
          });
          payment();
        })
        .catch((err) => {
          console.log(err);
          // dialogVisible.value = false;
          // ElMessage.error('编辑失败');
        });
    }
    // } else {
    //   console.log('error submit!');
    //   dialogVisible.value = false;
    //   ElMessage.error('操作失败');
    //   return false;
    // }
  });
};
// 取消
const submitForm = (formEl) => {
  console.log(formEl);
  if (!formEl) return;
  formEl.clearValidate();
  dialogVisible.value = false;
};

// 删除
const delete_cenyet = (item) => {
  console.log(item);
  ElMessageBox.confirm('你确定要删除该数据嘛？', '提示', {
    confirmButtonText: '确定删除',
    cancelButtonText: '我再想想',
    type: 'Warning',
  })
    .then(() => {
      delete_admin({
        id: item.id,
      })
        .then((res) => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          });
          payment();
        })
        .catch((err) => {
          ElMessage({
            type: 'error',
            message: '删除失败',
          });
        });
    })
    .catch(() => { });
};
</script>
<style scoped>
.top_navigate {
  display: flex;
  align-items: center;
}

.blue_ycy {
  width: 32px;
  height: 8px;
  background-color: #006eff;
  border-radius: 20px;
  margin-right: 10px;
}

.font_size {
  font-size: 20px;
}

.m-2 {
  width: 120px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #006eff;
}

.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.box-card {
  width: 100%;
}

.user_inp {
  width: 33.33%;
  display: flex;
  align-items: center;
}

.arrow {
  width: 96%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-left: 3%;
  height: 7vh;
}

.hide_box /deep/ .el-upload--picture-card {
  display: none;
}
</style>
